package com.luofan.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luofan.common.constant.RoleConstant;
import com.luofan.common.result.CustomException;
import com.luofan.common.result.ResultCodeEnum;
import com.luofan.common.util.JwtUtil;
import com.luofan.common.util.UserContext;
import com.luofan.entity.dto.UpdatePasswordDTO;
import com.luofan.entity.dto.UserQueryDTO;
import com.luofan.entity.po.User;
import com.luofan.entity.vo.LoginVO;
import com.luofan.entity.vo.UserVO;
import com.luofan.mapper.UserMapper;
import com.luofan.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-03-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;

    //登陆
    @Override
    public LoginVO login(User user) {
        //查询用户信息
        User userResult = userMapper.login(user);
        //查不到说明账号密码错误，返回null
        if (ObjectUtil.isEmpty(userResult)) return null;
        //如果Status为0说明账号被禁用
        if (userResult.getStatus() == 0) throw new CustomException(ResultCodeEnum.ACCOUNT_STOP);

        //生成token
        String token = jwtUtil.generateToken(userResult.getId(), userResult.getRole(), userResult.getSectionId());

        //封装VO返回
        LoginVO loginVO = new LoginVO();
        loginVO.setUser(userResult);
        loginVO.setToken(token);

        return loginVO;
    }

    //创建用户
    @Override
    public ResultCodeEnum createUser(User user) {
        //查询账号是否已存在
        int accountExistRows = userMapper.checkAccountExist(user.getAccount());
        if (accountExistRows > 0) return ResultCodeEnum.EXIST_ERROR;

        //如果创建的角色是教研室主任，先查看该教研室是否已有主任
        if (user.getRole() == RoleConstant.HEAD) {
            //根据教研室id 查看该教研室是否已有主任
            Long headId = userMapper.getSectionHead(user.getSectionId());
            //如果有，返回错误信息
            if (headId != null) return ResultCodeEnum.EXIST_HEAD_ERROR;
        }

        //创建用户
        int createUserRows = userMapper.createUser(user);
        if (createUserRows == 0) return ResultCodeEnum.FAIL;

        return ResultCodeEnum.SUCCESS;
    }

    //修改个人信息
    @Override
    public ResultCodeEnum updateUser(User user) {
        int rows = userMapper.updateUser(user);
        if (rows == 0) return ResultCodeEnum.FAIL;
        return ResultCodeEnum.SUCCESS;
    }

    //管理员 禁用，解禁用户
    @Override
    public ResultCodeEnum forbiddenUser(User user) {
        int rows = userMapper.forbiddenUser(user);
        if (rows == 0) return ResultCodeEnum.FAIL;
        return ResultCodeEnum.SUCCESS;
    }

    //重置密码
    @Override
    public ResultCodeEnum resetPasswords(Long id) {
        int rows = userMapper.resetPasswords(id);
        if (rows == 0) return ResultCodeEnum.FAIL;
        return ResultCodeEnum.SUCCESS;
    }

    //修改密码
    @Override
    public ResultCodeEnum updatePassword(UpdatePasswordDTO passwordDTO) {
        //判断原密码是否正确
        Long currentUserId = UserContext.getCurrentUserId();
        int count = userMapper.verifyPassword(currentUserId, passwordDTO.getOldPassword());
        //不正确返回错误信息
        if (count == 0) return ResultCodeEnum.PASSWORD_ERROR;

        //修改密码
        int rows = userMapper.updatePassword(currentUserId, passwordDTO.getNewPassword());
        if (rows == 0) return ResultCodeEnum.FAIL;

        return ResultCodeEnum.SUCCESS;
    }

    //管理员 更改教师所属教研室
    @Override
    public ResultCodeEnum updateUserSection(User user) {
        int rows = userMapper.updateUserSection(user);
        if (rows == 0) return ResultCodeEnum.FAIL;
        return ResultCodeEnum.SUCCESS;
    }

    //管理员 更改用户权限
    @Override
    public ResultCodeEnum updateUserRole(User user) {
        //如果从教师更改为教研室主任，先判断该角色所在教研室是否已有主任
        if (user.getRole() == RoleConstant.HEAD) {
            //判断所操作的用户所在教研室是否已有主任
            Long headId = userMapper.getUserHead(user.getId());
            //如果有，返回错误信息
            if (headId != null) return ResultCodeEnum.EXIST_HEAD_ERROR;
            //如果没有，先将该教研室主任id设置为此用户id
            int rows1 = userMapper.setSectionHeadId(user);
            if (rows1 == 0) return ResultCodeEnum.FAIL;
        }

        //更改用户权限
        int rows2 = userMapper.updateUserRole(user);
        if (rows2 == 0) return ResultCodeEnum.FAIL;

        //如果从主任更改为教师，则将用户所在教研室主任id设置为null
        if (user.getRole() == RoleConstant.TEACHER) {
            userMapper.clearSectionHeadId(user.getId());
        }

        return ResultCodeEnum.SUCCESS;
    }

    //管理员 根据条件 分页获取用户信息
    @Override
    public PageInfo<UserVO> listUserByCondition(UserQueryDTO userQueryDTO) {
        //进行分页拦截
        PageHelper.startPage(userQueryDTO.getPageNum(), userQueryDTO.getPageSize());

        //条件查询
        List<UserVO> userVoList = userMapper.listUserByCondition(userQueryDTO);

        //获取PageInfo
        PageInfo<UserVO> pageInfo = new PageInfo<>(userVoList);
        return pageInfo;
    }


}
